
import './PageAssembly.scss'
import { Pagination, Button, Tree, App, Upload } from 'antd'
import {
    ExportOutlined,
    CarryOutOutlined,
    PlusSquareOutlined,
    DeleteOutlined,
    AlignRightOutlined,
    RedoOutlined,
    AimOutlined,
    MenuUnfoldOutlined,
    UndoOutlined,
    SaveOutlined,
    BarChartOutlined
} from '@ant-design/icons'
import { useState } from 'react'

import { useRequest } from 'alova/client'

import { getTreeKeys, strOfurlParamsFunc } from '../Utils'
import { modelStore, drawerStore, refreshStore } from '../Config/zustand'
import { useMount } from 'ahooks'
import { Http, API_LIST } from './Api'
import { GetIndexedDB } from './IndexedDB'

import { saveAs } from 'file-saver'


const { port } = window.location


export const PagePagination = ({ total, Paging, DevEvent }) => {
    const { pageIndex: current, pageSize } = Paging
    return (
        <div className='PagePagination'>
            <Pagination
                align="end"
                showSizeChanger
                showTotal={(total, range) => `当前:${range[0]}-${range[1]} 共${total}条`}
                total={total}
                pageSizeOptions={[10, 20, 50, 100, 1000, 5000, 10000]}
                current={current}
                pageSize={pageSize}
                onChange={(pageIndex, pageSize) => DevEvent.emit({ type: 'onPagina', data: { pageIndex, pageSize } })}
            />
        </div>
    )
}


export const PageLeftMenu = ({ type, DevEvent }) => {
    const [expandedKeys, setExpandedKeys] = useState([])
    const [selectedKeys, setSelectedKeys] = useState([])

    const [treeData, setTreeData] = useState([])
    const { send } = useRequest(({ url }) => Http({ url }), { immediate: false })

    const onSelect = (e) => {
        if (e.length !== 0) {
            setSelectedKeys(e)
            DevEvent.emit({ type: 'onTree', data: e[0] })
        }
    }

    const onAll = () => setExpandedKeys(expandedKeys.length === 0 ? getTreeKeys(treeData, 'key') : [])

    const TreeMapping = {
        Organization: 'getOrganization',
        FlowTreeList: 'getFlowTreeList'
    }

    useMount(() => {
        send({ url: TreeMapping[type] }).then(res => {
            const data = JSON.parse(JSON.stringify(res.data.list).replace(/uuid/g, 'key').replace(/tableName/g, 'title'))
            setTreeData(data)
            setSelectedKeys([data[0].key])
            DevEvent.emit({ type: 'onTree', data: data[0].key })
            setExpandedKeys()
        })
    })
    return (
        <div className='PageLeftMenu' >
            <Button block icon={<MenuUnfoldOutlined />} onClick={onAll}>展开/收起</Button>
            <div className='Tree' >
                <Tree
                    blockNode={true}
                    onExpand={e => setExpandedKeys(e)}
                    expandedKeys={expandedKeys}
                    onSelect={onSelect}
                    selectedKeys={selectedKeys}
                    treeData={treeData}
                />
            </div>
        </div>
    )
}

export const PageTopOptions = ({ Config, DevEvent, searchData, init, wang }) => {
    const { notification } = App.useApp()
    const { updateModel } = modelStore()
    const { updateDrawer } = drawerStore()
    const { updateRefresh } = refreshStore()
    const { topOptions, fieldConfig } = Config
    const [Token, setToken] = useState()
    const [userUuid, setUserUuid] = useState()

    useMount(async () => {
        const user = await GetIndexedDB('user')
        setUserUuid(user.userUuid)
    })


    const optionsMapping = {
        batchReviewStatus: { title: '批量审核', icon: <CarryOutOutlined style={{ color: 'rgba(251, 154, 14, 1)' }} /> },
        batchActivationStatus: { title: '批量启用', icon: <CarryOutOutlined style={{ color: 'rgba(251, 154, 14, 1)' }} /> },
        batchDeletionStatus: { title: '批量删除', icon: <DeleteOutlined style={{ color: 'rgba(229, 72, 77, 1)' }} /> },
        addedStatus: { title: '添加信息', icon: <PlusSquareOutlined style={{ color: 'rgba(48, 164, 108, 1)' }} /> },
        refreshStatus: { title: '刷新信息', icon: <RedoOutlined style={{ color: 'rgba(19, 194, 194, 1)' }} /> },
        sortStatus: { title: '信息排序', icon: <AlignRightOutlined style={{ color: 'rgba(19, 194, 194, 1)' }} /> },
        queryStatus: { title: '信息查询', icon: <AimOutlined style={{ color: 'rgba(255, 169, 64, 1)' }} /> },
    }

    const [selectedRowKeys, setSelectedRowKeys] = useState([])
    DevEvent.useSubscription(val => {
        const { type, data } = val
        if (type === 'onSelectionChanged') setSelectedRowKeys(data)
    })

    const { send } = useRequest(data => Http(data), { immediate: false })

    const onClick = (key) => {
        const { batchReviewName, batchReviewUrl, batchReviewParams, batchActivationOptName, batchReviewTemp } = topOptions
        switch (key) {
            case 'batchReviewStatus':
                if (selectedRowKeys.length === 0) {
                    notification.info({ key: 'optionsInfo', message: '操作警告', description: '请先选择数据!' })
                    return false
                }
                if (batchReviewTemp === 'BatchExcelModigy') {
                    const params = { url: { get: 'posGetBatchExcelTemp', pos: 'posUploadExcel', params: selectedRowKeys } }
                    updateModel({ title: '批量修改', type: 'FromExcel', width: '90vw', data: params })
                } else {
                    updateModel({
                        title: batchReviewName,
                        modalType: 'model',
                        type: 'Additional',
                        width: 600,
                        data: { type: 'batchReviewTemp', init: selectedRowKeys, params: { batchReviewUrl, batchReviewParams } }
                    })
                }
                break;
            case 'batchActivationStatus':
                if (selectedRowKeys.length === 0) {
                    notification.info({ key: 'optionsInfo', message: '操作警告', description: '请先选择数据!' })
                    return false
                }
                if (wang) {
                    if (wang === userUuid) updateModel({ title: batchActivationOptName, type: 'BatchIsEnabled', data: { options: topOptions, init: selectedRowKeys } })
                    else updateModel({ title: batchActivationOptName, type: 'BatchIsEnabled', data: { options: { ...topOptions, batchActivationBtnMap: 'isUnlock' }, init: selectedRowKeys } })
                } else updateModel({ title: batchActivationOptName, type: 'BatchIsEnabled', data: { options: topOptions, init: selectedRowKeys } })
                break;
            case 'batchDeletionStatus':
                if (selectedRowKeys.length === 0) {
                    notification.info({ key: 'optionsInfo', message: '操作警告', description: '请先选择数据!' })
                    return false
                }
                const { batchDeletionUrl, batchDeletionParams } = topOptions
                updateModel({ title: '批量删除', type: 'BatchRemove', data: { url: batchDeletionUrl, params: batchDeletionParams, init: selectedRowKeys } })
                break;
            case 'addedStatus':
                const { addedType, addedUrl, addedExcel, addedParams, addedTable } = topOptions
                if (addedType === 'form') {
                    const params = addedParams ? { [addedParams]: init.uuid } : {}
                    updateModel({ title: '添加信息', type: 'FromModify', data: { url: addedUrl, fields: fieldConfig, params } })
                }
                else if (addedType === 'excel') updateModel({ title: '添加信息', type: 'FromExcel', width: '90vw', data: { url: { get: addedExcel, pos: addedUrl, params: addedParams } } })
                else if (addedType === 'table') {
                    updateModel({ title: '选择用户', type: 'TableSelect', width: '80vw', data: { type: addedUrl, init: { data: init, addedParams } } })
                }
                break;
            case 'refreshStatus': updateRefresh(new Date().getTime()); break
            case 'sortStatus': updateDrawer({ title: '信息排序', type: 'SortBox', data: { data: Config.sortConfig, DevEvent } }); break
            case 'queryStatus': updateDrawer({ title: '信息查询', type: 'SearchBox', data: { data: Config.searchConfig, fields: fieldConfig, searchData, DevEvent } }); break
            default: break;
        }
    }

    const downExcel = () => {
        const { exportUrl, exportName } = topOptions
        updateModel({ title: exportName || 'Excel预览', type: 'FromExcel', width: '90vw', data: { url: { get: exportUrl, params: searchData } } })
    }

    useMount(async () => {
        const token = await GetIndexedDB('token')
        setToken(token)
    })

    const onAntV = () => {
        updateModel({ title: '脑图图例', type: 'GraphCharts', width: '90vw' })
    }

    return (
        <div className='PageTopOptions'>
            <div className='excel'>
                {topOptions.exportStatus && <Button type='link' icon={<ExportOutlined />} onClick={downExcel}>{topOptions.exportName || '导出excel模板'}</Button>}
                {/* {port && <Button type='link' icon={<ExportOutlined />} onClick={onAntV}>脑图</Button>} */}
            </div>
            <div className='options'>
                {Object.keys(optionsMapping).map(key => {
                    if (topOptions[key]) {
                        const { addedType, batchActivationOptName, batchReviewName } = topOptions
                        const DataTemp = (<Button key={key} type='link' icon={optionsMapping[key].icon} onClick={() => onClick(key)}>{optionsMapping[key].title}</Button>)
                        if (key === 'addedStatus' && addedType === 'file') {
                            const props = {
                                name: 'File',
                                action: API_LIST()['posAttachment'],
                                headers: { Authorization: Token },
                                data: { AnnexUuid: init.uuid },
                                maxCount: 1,
                                showUploadList: false,
                                onChange(info) {
                                    notification.info({ key: 'optionsInfo', showProgress: true, message: '正在上传!', description: '附件上传中...!' })
                                    if (info.file.status === 'done') {
                                        updateRefresh(new Date().getTime())
                                        notification.success({ key: 'optionsInfo', message: '操作成功!', description: '附件已上传!' })
                                    } else if (info.file.status === 'error') {
                                        notification.error({ key: 'optionsInfo', message: '操作失败!', description: '附件上传失败!' })
                                    }
                                },
                            };
                            return (<Upload key={key} {...props}><Button type='link' icon={optionsMapping[key].icon} >{optionsMapping[key].title}</Button></Upload>)
                        }

                        if (key === 'batchActivationStatus') {
                            return (<Button key={key} type='link' icon={optionsMapping[key].icon} onClick={() => onClick(key)}>{batchActivationOptName}</Button>)
                        }
                        if (key === 'batchReviewStatus') {
                            return (<Button key={key} type='link' icon={optionsMapping[key].icon} onClick={() => onClick(key)}>{batchReviewName}</Button>)
                        }
                        return DataTemp
                    } else {
                        return false
                    }
                })}
            </div>
        </div>
    )
}

export const PageOlapOptions = ({ Config, searchData, DevEvent }) => {
    const { notification } = App.useApp()
    const { topOptions, fieldConfig } = Config
    const { updateModel } = modelStore()
    const { updateDrawer } = drawerStore()
    const layoutOptions = {
        olapLayout: { title: '保存布局', icon: <SaveOutlined style={{ color: '#237804' }} /> },
        resetLayout: { title: '重置布局', icon: <UndoOutlined style={{ color: '#f5222d' }} /> },
    }
    const optionsMapping = {
        charts: { title: '数据图表', icon: <BarChartOutlined style={{ color: '#003eb3' }} /> },
        queryStatus: { title: '信息查询', icon: <AimOutlined style={{ color: 'rgba(255, 169, 64, 1)' }} /> },
    }

    const { send: posJson } = useRequest(params => Http({ url: 'posJSONData', params }), { immediate: false })

    const onClick = (key) => {
        const { tableConfig } = Config
        const { pageUrl } = tableConfig
        switch (key) {
            case 'olapLayout':
                const initData = JSON.parse(sessionStorage.getItem(pageUrl)).fields.filter(v => v.area)
                posJson({ Uuid: `OLAPLayout/${pageUrl}`, Content: JSON.stringify(initData) }).then(() => {
                    notification.success({ key: 'optionsInfo', message: '操作成功', description: `${pageUrl}页面默认布局保存成功!` })
                })
                break;
            case 'resetLayout':
                sessionStorage.removeItem(pageUrl)
                window.location.reload()
                break;

            case 'charts':
                updateModel({ title: '图例信息', type: 'DEVCharts', width: '90vw' })
            case 'queryStatus': updateDrawer({ title: '信息查询', type: 'SearchBox', data: { data: Config.searchConfig, fields: fieldConfig, searchData, DevEvent } }); break
            default: break;
        }
    }

    return (
        <div className='PageTopOptions'>
            <div className='excel'>
                {Object.keys(layoutOptions).map(key => {
                    if (topOptions[key]) {
                        return <Button key={key} type='link' icon={layoutOptions[key].icon} onClick={() => onClick(key)}>{layoutOptions[key].title}</Button>
                    }
                })}
            </div>
            <div className='options'>
                {Object.keys(optionsMapping).map(key => {
                    if (topOptions[key]) {
                        return <Button key={key} type='link' icon={optionsMapping[key].icon} onClick={() => onClick(key)}>{optionsMapping[key].title}</Button>
                    }
                })}
            </div>
        </div>
    )
}
